package productproperty

import (
	// "net/http"

	"strconv"

	// "time"
	// "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"

	// "github.com/jinzhu/gorm"

	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/dicserver/property"
	"oxy_server/until"
)

type (
	productproperty struct {
		ID                bson.ObjectId       `json:"_id" bson:"_id"`
		DesignPlanID      string              `json:"designplanid" bson:"designplanid"`           //设计组ID
		ProductPlanID     string              `json:"productplanid" bson:"productplanid"`         //生产组ID
		ReferenceBigTag   string              `json:"referencebigtag" bson:"referencebigtag"`     //参考大牌
		SellingPoints     string              `json:"sellingpoints" bson:"sellingpoints"`         //卖点
		DesignManufacture string              `json:"designmanufacture" bson:"designmanufacture"` //设计与工艺
		StereoType        []string            `json:"stereotype" bson:"stereotype"`               //版型
		ProductName       string              `json:"productname" bson:"productname"`             //商品名称
		Compose           []Compose           `json:"compose" bson:"compose"`                     //组成
		DesignComposeInfo []property.Property `json:"composeinfo" bson:"composeinfo"`             //组成详细
		AddCompose        []Compose           `json:"addcompose" bson:"addcompose"`               //生产组补充组成
		PackageCost       []Compose           `json:"packagecost" bson:"packagecost"`             //组成
		TransportCost     []Compose           `json:"processcost" bson:"processcost"`             //组成
		PropertyStatus    int                 `json:"propertystatus" bson:"propertystatus"`       //产品属性编辑状态
		Cloth             string              `json:"cloth" bson:"cloth"`                         //面料
		Process           string              `json:"process" bson:"process"`                     //工艺
		Match             string              `json:"match" bson:"match"`                         //搭配
		Version           string              `json:"version" bson:"version"`                     //版型
	}
	insertproductproperty struct {
		DesignPlanID      string              `json:"designplanid" bson:"designplanid"`           //设计组ID
		ProductPlanID     string              `json:"productplanid" bson:"productplanid"`         //生产组ID
		ReferenceBigTag   string              `json:"referencebigtag" bson:"referencebigtag"`     //参考大牌
		SellingPoints     string              `json:"sellingpoints" bson:"sellingpoints"`         //卖点
		DesignManufacture string              `json:"designmanufacture" bson:"designmanufacture"` //设计与工艺
		StereoType        []string            `json:"stereotype" bson:"stereotype"`               //版型
		ProductName       string              `json:"productname" bson:"productname"`             //商品名称
		Compose           []Compose           `json:"compose" bson:"compose"`                     //组成
		DesignComposeInfo []property.Property `json:"composeinfo" bson:"composeinfo"`             //组成详细
		AddCompose        []Compose           `json:"addcompose" bson:"addcompose"`               //生产组补充组成
		PackageCost       []Compose           `json:"packagecost" bson:"packagecost"`             //组成
		ProcessCost       []Compose           `json:"processcost" bson:"processcost"`             //组成
		PropertyStatus    int                 `json:"propertystatus" bson:"propertystatus"`       //产品属性编辑状态
		Cloth             string              `json:"cloth" bson:"cloth"`                         //面料
		Process           string              `json:"process" bson:"process"`                     //工艺
		Match             string              `json:"match" bson:"match"`                         //搭配
		Version           string              `json:"version" bson:"version"`                     //版型
	}
	Compose struct {
		Item          string `json:"item" bson:"item"`                   //项目
		Specification string `json:"specification" bson:"specification"` //规格描述
		Quantity      string `json:"quantity" bson:"quantity"`           //用量
		Loss          string `json:"loss" bson:"loss"`                   //损耗
		UnitPrice     string `json:"unitprice" bson:"unitprice"`         //单价
		Cost          string `json:"cost" bson:"cost"`                   //单项成本
		Provider      string `json:"provider" bson:"provider"`           //供应商
	}
)

type OXYProductPropertyData struct{}

func NewOXYProductPropertyData() *OXYProductPropertyData {
	productPropertyData := &OXYProductPropertyData{}
	return productPropertyData
}

func (opd *OXYProductPropertyData) GetProductPropertyListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_property"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().Query(M, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []productproperty{}
	query.All(&ps)
	for index, item := range ps {
		queryList := []bson.M{}
		for _, c := range item.Compose {
			obj := bson.M{"_id": bson.ObjectIdHex(c.Item)}
			queryList = append(queryList, obj)
		}
		model.DB().Dbname = "OxyDic"
		model.DB().Document = "Property"
		propertyInfoQuery, _, err := model.DB().Query(bson.M{"$or": queryList}, 0, 0)
		if err != nil {
			log.Error("查询出错", err)
		}
		propertyInfo := []property.Property{}
		propertyInfoQuery.All(&propertyInfo)
		ps[index].DesignComposeInfo = propertyInfo
	}
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  ps,
		"count": count,
	})

	return nil
}

func (opd *OXYProductPropertyData) AddProductPropertyHandler(c echo.Context) error {
	o := &insertproductproperty{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_property"
	err := model.DB().Insert(o)

	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	//更新过会组状态
	model.DB().Document = "product_plan"
	selector := bson.M{"_id": bson.ObjectIdHex(o.ProductPlanID)}
	data := bson.M{"$set": bson.M{"propertystatus": o.PropertyStatus}}
	_, err = model.DB().UpdateAll(selector, data)

	if err != nil {
		log.Error("更新 product_plan propertystatus 出错", err)
		c.JSON(400, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}
func (opd *OXYProductPropertyData) UpdateProductPropertyHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateProductPropertyHandler", id)

	o := &insertproductproperty{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_property"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, o)
	//更新过会组状态
	model.DB().Document = "product_plan"
	selector := bson.M{"_id": bson.ObjectIdHex(o.ProductPlanID)}
	data := bson.M{"$set": bson.M{"propertystatus": o.PropertyStatus}}
	_, err = model.DB().UpdateAll(selector, data)

	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYProductPropertyData) DelProductPropertyHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelProductPropertyHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_property"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
